//
//  CreateJobModelHelper.swift
//  GreenDeal
//
//  Created by Moennig Q on 2/3/2023.
//

import UIKit
import RxRelay
import RxSwift
import SwiftyJSON
import HandyJSON
class CreateJobModelHelper {
    //MARK: - 单例
    static let shared = CreateJobModelHelper()
    //
    var createJobViewModel = CreateJobViewModel()
    //观察对象
    var systemInfoObserver: PublishSubject<SystemDetailViewModel> = PublishSubject()//观察对象
    var installerDetailObserver: PublishSubject<CreateJobInstallerViewModel> = PublishSubject()
    
    let group = DispatchGroup()
    //MARK: - 校验installer是否是有效的数据，company id有关系
    func checkIfInstallDetailValid(loadingFlag: Bool = false, _ closure: ((String?)->Void)? = nil){
        let companyID = CreateJobModelHelper.shared.createJobViewModel.summaryViewModel.company_id
        let installerID = CreateJobModelHelper.shared.createJobViewModel.installerDetail.installerID
        let designerID = CreateJobModelHelper.shared.createJobViewModel.installerDetail.designerID
        let electricianID = CreateJobModelHelper.shared.createJobViewModel.installerDetail.electricianID
        let deliveryAddressID = CreateJobModelHelper.shared.createJobViewModel.installerDetail.delivery_address_id
        
        //
        var allInstallers = [MyInformationModel]()
        var allDesigners = [MyInformationModel]()
        var allElectricians = [MyInformationModel]()
        //
        var allDeliveryWarehouseList = [DeliveryWarehouseModel]()
        //
        var errCode = ""
        var errMsg = ""
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView("Validating...")
        }
        //installer
        if installerID > 0{
            group.enter()
            self.getUsersList(.installer, companyID: companyID) { list, code,msg in
                if let list = list {
                    allInstallers = list
                }else if let msg = msg, let code = code{
                    errCode = code
                    errMsg = msg
                }
                self.group.leave()
            }
        }
        //designer
        if designerID > 0{
            group.enter()
            self.getUsersList(.designer, companyID: companyID) { list, code,msg in
                if let list = list {
                    allDesigners = list
                }else if let msg = msg, let code = code{
                    errCode = code
                    errMsg = msg
                }
                self.group.leave()
            }
        }
        //electrician
        if electricianID > 0{
            group.enter()
            self.getUsersList(.electrician, companyID: companyID) { list, code,msg in
                if let list = list {
                    allElectricians = list
                }else if let msg = msg, let code = code{
                    errCode = code
                    errMsg = msg
                }
                self.group.leave()
            }
        }
        //pick up delivery address
        let pickUpRequired = CreateJobModelHelper.shared.createJobViewModel.installerDetail.pickupRequired
        let deliveryWarehouseType = CreateJobModelHelper.shared.createJobViewModel.installerDetail.address_type
        if pickUpRequired && deliveryWarehouseType == .other {
            group.enter()
            self.getDeliverWarehouseList(deliveryWarehouseType, companyID: companyID) { list, code,msg  in
                if let list = list {
                    allDeliveryWarehouseList = list
                }else if let msg = msg, let code = code{
                    errCode = code
                    errMsg = msg
                }
                self.group.leave()
            }
        }
        
        self.group.notify(queue: DispatchQueue.main) {
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            if errCode != "" || errMsg != "" {
                closure?(errMsg)
            }else{
                //installer
                if let _ = allInstallers.firstIndex(where: {$0.id == installerID}) {
                    CreateJobModelHelper.shared.createJobViewModel.installerDetail.installer_valid_flag = true
                }else{
                    CreateJobModelHelper.shared.createJobViewModel.installerDetail.installer_valid_flag = false
                }
                //designer
                if let _ = allDesigners.firstIndex(where: {$0.id == designerID}) {
                    CreateJobModelHelper.shared.createJobViewModel.installerDetail.designer_valid_flag = true
                }else{
                    CreateJobModelHelper.shared.createJobViewModel.installerDetail.designer_valid_flag = false
                }
                //electrician
                if let _ = allElectricians.firstIndex(where: {$0.id == electricianID}) {
                    CreateJobModelHelper.shared.createJobViewModel.installerDetail.electrician_valid_flag = true
                }else{
                    CreateJobModelHelper.shared.createJobViewModel.installerDetail.electrician_valid_flag = false
                }
                //pick up address
                if pickUpRequired && deliveryWarehouseType == .other {
                    if let _ = allDeliveryWarehouseList.firstIndex(where: {$0.id == deliveryAddressID}) {
                        CreateJobModelHelper.shared.createJobViewModel.installerDetail.delivery_address_valid_flag = true
                    }else{
                        CreateJobModelHelper.shared.createJobViewModel.installerDetail.delivery_address_valid_flag = false
                    }
                }
                CreateJobModelHelper.shared.installerDetailObserver.onNext(CreateJobModelHelper.shared.createJobViewModel.installerDetail)
            }
        }
    }
    //MARK: - get installer,designer , electricial
    private func getUsersList(_ type: SearchInstallerType,companyID: Int,closure: (([MyInformationModel]?,String?,String?)->Void)? = nil){
        let vm = DictionaryService()
        vm.setBlockAfterNetwork { (result, _) in
            if let list = result as? [MyInformationModel]{
                closure?(list,nil,nil)
            }
        } errorBlock: { (code, error) in
            closure?(nil, code, error)
        }
        if type == .installer {
            vm.getInstallerList(companyId: companyID)
        }else if type == .designer{
            vm.getDesignerList(companyId: companyID)
        }else if type == .electrician{
            vm.getElectricianList(companyId: companyID)
        }
    }
    //MARK: - 根据search value获取address list
    private func getDeliverWarehouseList(_ deliverWarehouseType: DeliveryWarehouseType, companyID: Int,closure: (([DeliveryWarehouseModel]?,String?,String?)->Void)? = nil){
        let vm = DictionaryService()
        vm.setBlockAfterNetwork {(result, _) in
            if let list = result as? Array<DeliveryWarehouseModel>{
                closure?(list, nil, nil)
            }
        } errorBlock: {  (code, error) in
            closure?(nil, code, error)
        }
        vm.getDeliveryList(deliveryWarehouseType: deliverWarehouseType, companyID: companyID)
    }
    //MARK: - 校验panels，inverter是否是有效的数据，scheduled date有关系(注意battery没有安装日期)
    func checkIfSystemInfoValid(loadingFlag: Bool = false, _ closure: ((String?)->Void)? = nil){
        let installDate = CreateJobModelHelper.shared.createJobViewModel.installDate
        let panels = CreateJobModelHelper.shared.createJobViewModel.systemDetail.panels
        let inverters = CreateJobModelHelper.shared.createJobViewModel.systemDetail.inverters
        //panels
        for model in panels{
            model.valid_flag = self.checkIfModelValid(installDate: installDate, modelApprovedDateStr: model.approved_date, modelExpiryDateStr: model.expiry_date)
        }
        //inverter
        for model in inverters{
            model.valid_flag = self.checkIfModelValid(installDate: installDate, modelApprovedDateStr: model.approved_date, modelExpiryDateStr: model.expiry_date)
        }
        CreateJobModelHelper.shared.systemInfoObserver.onNext(CreateJobModelHelper.shared.createJobViewModel.systemDetail)
    }
    //MARK: - 检验model是否有效，install date在过期之前就是有效
    private func checkIfModelValid(installDate: Date, modelApprovedDateStr: String, modelExpiryDateStr: String)->Bool{
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        if let modelApprovedDate = formatter.date(from: modelApprovedDateStr),let modelExpiryDate = formatter.date(from: modelExpiryDateStr){
            let intervalInstallDate = installDate.timeIntervalSince1970
            let intervalModelApprovedDate = modelApprovedDate.timeIntervalSince1970
            let intervalModelExpiryDate = modelExpiryDate.timeIntervalSince1970
            if intervalModelExpiryDate > intervalInstallDate && intervalInstallDate > intervalModelApprovedDate{
                return true
            }else{
                return false
            }
        }
        return true
    }
    //MARK: - get panels,inverters , battery
    private func getDictionaryModelsList(_ type: SearchModelType,installDate: String,closure: (([SearchDictionaryModel]?,String?,String?)->Void)? = nil){
        let vm = DictionaryService()
        vm.setBlockAfterNetwork { (result, _) in
            let json = JSON(result!)
            if let list = JSONDeserializer<SearchDictionaryModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<SearchDictionaryModel>{
                closure?(list,nil,nil)
            }
        } errorBlock: { (code, error) in
            closure?(nil,code,error)
        }
        if type == .inverter {
            vm.getInverterModels("",installationDate: installDate)
        }else if type == .panel{
            vm.getPanelModels("",installationDate: installDate)
        }else if type == .battery{
            vm.getBatteryModels("",installationDate: installDate)
        }
    }
}
